package com.dd.ent.car.common.player;

import android.os.Handler;
import android.util.Log;


import java.util.LinkedList;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Author:LiuJianSheng
 * Date:2016/6/1
 */
public class PlayerStateManager {
    private Handler mMainThreadHandler;
    private final AtomicReference<MediaPlayerState> mState = new AtomicReference<>(MediaPlayerState.IDLE);
    private boolean isPrepared;

    private LinkedList<MediaPlayerStateChangeListener> stateChangeListenerList = new LinkedList<>();

    public PlayerStateManager(Handler mainThreadHandler) {
        this.mMainThreadHandler = mainThreadHandler;
    }

    public synchronized MediaPlayerState getState() {
        return mState.get();
    }

    public synchronized void setState(MediaPlayerState state) {
        MediaPlayerState oldState = mState.get();
        if (oldState != state) {
            switch (state) {
                case IDLE:
                case STOPPED:
                    isPrepared = false;
                    break;
                case PREPARED:
                    isPrepared = true;
                    break;
            }
            this.mState.set(state);
            notifyStateChange(oldState, state);
        }
    }

    public void addStateChangeListener(MediaPlayerStateChangeListener listener) {
        if (listener != null && !stateChangeListenerList.contains(listener)) {
            stateChangeListenerList.add(listener);
        }
    }

    public void removeStateChangeListener(MediaPlayerStateChangeListener listener) {
        if (listener != null) {
            stateChangeListenerList.remove(listener);
        }
    }

    private void notifyStateChange(final MediaPlayerState oldState, final MediaPlayerState newState) {
        if (stateChangeListenerList.isEmpty()) {
            return;
        }
        boolean isInUiThread = MediaPlayerUtils.isInUiThread();
        if (isInUiThread) {
            Log.d(MediaPlayerWrapper.TAG, "onStateChange--oldState=" + oldState + "|newState=" + newState);
            for (MediaPlayerStateChangeListener listener : stateChangeListenerList) {
                listener.onStateChange(oldState, newState);
            }
        } else {
            mMainThreadHandler.post(new Runnable() {
                @Override
                public void run() {
                    Log.d(MediaPlayerWrapper.TAG, "onStateChange--oldState=" + oldState + "|newState=" + newState);
                    for (MediaPlayerStateChangeListener listener : stateChangeListenerList) {
                        listener.onStateChange(oldState, newState);
                    }
                }
            });
        }
    }

    public boolean isPrepared() {
        return isPrepared;
    }

    public boolean isPlaying() {
        return mState.get() == MediaPlayerState.STARTED;
    }

    public boolean isReleased() {
        return mState.get() == MediaPlayerState.RELEASE;
    }
}
